package com.wenhua.mail.service.impl;

import java.util.Date;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.wenhua.mail.service.MailService;
import com.wenhua.mail.utils.RandomUtil;

/**
 * @Description
 * @Author ycq
 * @Create 2020-03-31 09:57
 * @Version 1.0
 **/
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String form;

    private static final String SUBJECT = "纹化商城";

    @Override
    public String sendHtmlMail(String to) throws Exception {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject(SUBJECT);
        helper.setFrom(form);
        helper.setTo(to);
        helper.setSentDate(new Date());
        Context context = new Context();
        String generate = RandomUtil.generate();
        context.setVariable("random", generate);
        String process = templateEngine.process("Mail.html", context);
        helper.setText(process, true);
        javaMailSender.send(mimeMessage);
        return generate;
    }

    @Override
    public boolean sendHtmlLink(String to, String url) throws Exception {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject(SUBJECT);
        helper.setFrom(form);
        helper.setTo(to);
        helper.setSentDate(new Date());
        Context context = new Context();
        context.setVariable("url", url);
        String process = templateEngine.process("MailLink.html", context);
        helper.setText(process, true);
        javaMailSender.send(mimeMessage);
        return true;
    }
}